<template>
  <div>
    <q-form class="sc-edit">
      <yq-table
        v-model:search="searchForm"
        v-model:table="tableOptions"
        v-model:initial="initialPagination"
        @onRequest="onRequest"
        @search="goodsListInit"
        :topAdd="false"
        :isStatus="'goods_state'"
        :topOptions="[
          { value: '', label: '全部' },
          { value: 0, label: '待审核' },
          { value: 1, label: '上架' },
          { value: 2, label: '不通过' },
          { value: 3, label: '下架' },
        ]"
      >
        <template v-slot:yq_table_body="props">
          <q-tr :props="props.props">
            <q-td key="goods_id" :props="props.props">
              <span>{{ props.props.row.goods_id }}</span>
            </q-td>

            <q-td key="goods_name" :props="props.props">
              <span>{{ props.props.row.goods_name }}</span>
            </q-td>

            <q-td key="goods_image" :props="props.props">
              <q-avatar v-if="props.props.row.goods_image">
                <el-image
                  style="width: 50px; height: 50px"
                  :src="props.props.row.goods_image"
                  :preview-src-list="[props.props.row.goods_image]"
                  hide-on-click-modal
                  preview-teleported
                  :initial-index="1"
                  fit="cover"
                />
              </q-avatar>
            </q-td>

            <q-td key="goods_state" :props="props.props">
              <span>{{
                props.props.row.goods_state == 0
                  ? '待审核'
                  : props.props.row.goods_state == 1
                  ? '上架'
                  : props.props.row.goods_state == 2
                  ? '不通过'
                  : '下架'
              }}</span>
            </q-td>

            <q-td key="price" :props="props.props">
              <span>{{ props.props.row.price }}</span>
            </q-td>

            <q-td key="market_price" :props="props.props">
              <span>{{ props.props.row.market_price }}</span>
            </q-td>

            <q-td key="cost_price" :props="props.props">
              <span>{{ props.props.row.cost_price }}</span>
            </q-td>

            <q-td key="goods_stock" :props="props.props">
              <span>{{ props.props.row.goods_stock }}</span>
            </q-td>

            <q-td key="is_free_shipping" :props="props.props">
              <span>{{
                props.props.row.is_free_shipping == 1 ? '是' : '否'
              }}</span>
            </q-td>

            <q-td key="unit" :props="props.props">
              <span>{{ props.props.row.unit }}</span>
            </q-td>

            <q-td key="type_name" :props="props.props">
              <span>{{ props.props.row.type_name }}</span>
            </q-td>

            <q-td key="created_at" :props="props.props">
              <span>{{ props.props.row.created_at }}</span>
            </q-td>

            <q-td key="operation" :props="props.props">
              <q-btn
                flat
                round
                dense
                color="primary"
                icon="remove_red_eye"
                v-permission="'/goods/Recycle:detail'"
                @click="edit(props.props.row.id, props.props.row)"
              >
                <q-tooltip>查看</q-tooltip>
              </q-btn>

              <q-btn
                flat
                round
                dense
                color="primary"
                icon="reply"
                v-permission="'/goods/Recycle:restore'"
              >
                <q-tooltip>恢复</q-tooltip>
                <q-menu
                  transition-show="jump-up"
                  transition-hide="jump-down"
                  content-class="text-center"
                  self="bottom left"
                  anchor="top left"
                  :offset="[60, 5]"
                >
                  <div class="q-px-sm q-pt-md">
                    <q-icon name="info" color="warning" class="q-mr-sm" />
                    恢复该商品吗?
                  </div>
                  <div class="q-gutter-x-sm q-pt-sm q-pb-md">
                    <q-btn
                      color="grey-6"
                      unelevated
                      class="no-border-radius text-body2"
                      padding="2px sm"
                      dense
                      label="取消"
                      v-close-popup
                    ></q-btn>
                    <q-btn
                      color="primary"
                      unelevated
                      class="no-border-radius text-body2"
                      padding="2px sm"
                      dense
                      label="确认"
                      @click="recovery(props.props.row)"
                      v-close-popup
                    ></q-btn>
                  </div>
                </q-menu>
              </q-btn>

              <q-btn
                flat
                round
                dense
                class="q-mx-xs"
                color="negative"
                icon="delete"
                v-permission="'/goods/Recycle:delete'"
              >
                <q-menu
                  transition-show="jump-up"
                  transition-hide="jump-down"
                  content-class="text-center"
                  self="bottom left"
                  anchor="top left"
                  :offset="[60, 5]"
                >
                  <div class="q-px-sm q-pt-md">
                    <q-icon name="info" color="warning" class="q-mr-sm" />
                    是否要删除此行?
                  </div>
                  <div class="q-gutter-x-sm q-pt-sm q-pb-md">
                    <q-btn
                      color="grey-6"
                      unelevated
                      class="no-border-radius text-body2"
                      padding="2px sm"
                      dense
                      label="取消"
                      v-close-popup
                    ></q-btn>
                    <q-btn
                      color="primary"
                      unelevated
                      class="no-border-radius text-body2"
                      padding="2px sm"
                      dense
                      label="确认"
                      @click="deleteData(props.props.row.id, props.props.row)"
                      v-close-popup
                    ></q-btn>
                  </div>
                </q-menu>
              </q-btn>
            </q-td>
          </q-tr>
        </template>
      </yq-table>
    </q-form>
    <yq-dialog
      v-model:lockDialog="lockDialog"
      :title="title"
      fulls
      :bottomBtn="false"
    >
      <template v-slot:yq_dialog_body
        ><recycle-dialog
          :form="formRole"
          @backList="goodsListInit"
          :useroptions="useroptions"
          :cateoptions="cateoptions"
          :goodsTypeoptions="goodsTypeoptions"
      /></template>
    </yq-dialog>
  </div>
</template>

<script setup lang="ts">
import { listData, pageInit, listDataSku } from '../mocklist';
import {
  recycleList,
  recycleDelete,
  categoryAll,
  goodsTypeAll,
  recycleDetail,
  recycleRestore,
} from '@/api/goods';
import RecycleDialog from './RecycleDialog.vue';
import { Ref } from 'vue';
import { useQuasar } from 'quasar';
import { cloneDeep } from 'lodash-es';

// let advancedFormData = reactive(userData);
// console.log('2322222', advancedFormData);
interface formRoleProps {
  goods_name?: string; //商品名称
  category_id?: any; //分类id
  goods_type?: number; //商品类型id
  goods_image?: string; //商品主图
  goods_content?: string; //商品详情
  is_free_shipping?: number; //是否免邮
  unit?: string; //台
  goods_sort?: number; //排序
  goods_state?: any; //商品状态（0:待审核,1:上架,2:审核不通过,3:下架）
  goods_attr_format?: Array<any>; //商品属性
  goods_spec_format?: Array<any>; //商品规格
  sku?: Array<any>; //商品sku
  images?: Array<any>; //商品图片
  tinymceID?: any;
}

const tableOptions = reactive({
  tableLoading: false,
  ...listData,
});
const initialPagination = ref(cloneDeep(pageInit));
const lockDialog = ref(false);
const title = ref('新建商品');
const formRole: Ref<formRoleProps> = ref({});
const $q = useQuasar();
const useroptions: any = ref([]);
const group: any = ref([]);
const cateoptions: any = ref([]); //所有分类
const goodsTypeoptions: any = ref([]); //商品分类

const searchForm = reactive({
  keywords: '',
  search: {
    goods_state: '',
  },
  dateMin: {
    created_at: '',
  },
  dateMax: {
    created_at: '',
  },
});

tableOptions.columns.forEach(({ name }) => {
  group.value.push(name);
});
// const save = (index: number) => {
//   console.log(index);
// };
const add_popover_bool = ref(false); // 添加属性的小弹窗

const add = () => {
  title.value = '新建商品';
  formRole.value = {
    goods_state: 0,
    tinymceID:
      'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + ''),
    goods_attr_format: [],
    goods_spec_format: [],
    is_free_shipping: 1,
    sku: [],
    images: [
      // {
      //   type: 0,
      //   link: 'https://img10.360buyimg.com/seckillcms/s144x144_jfs/t1/149566/7/24992/72455/62285595E0686825a/04ced0fe352c2d9d.jpg!q70.jpg.webp',
      // },
      // {
      //   type: 0,
      //   link: 'http://test.yuanqi.3qma.com/uploads/admin/image/202207/c093082ed79f963eede63501cf3f5687.jpg',
      // },
      // {
      //   type: 1,
      //   link: 'http://test.yuanqi.3qma.com/uploads/admin/video/202207/2a39a14efb52276e58bcf51e6dc1d4b8.mp4',
      // },
      // {
      //   type: 1,
      //   link: 'http://test.yuanqi.3qma.com/uploads/admin/video/202207/2a39a14efb52276e58bcf51e6dc1d4b8.mp4',
      // },
      // {
      //   type: 0,
      //   link: 'http://test.yuanqi.3qma.com/uploads/admin/image/202207/c093082ed79f963eede63501cf3f5687.jpg',
      // },
      // {
      //   type: 0,
      //   link: 'http://test.yuanqi.3qma.com/uploads/admin/image/202207/c093082ed79f963eede63501cf3f5687.jpg',
      // },
      // {
      //   type: 0,
      //   link: 'http://test.yuanqi.3qma.com/uploads/admin/image/202207/c093082ed79f963eede63501cf3f5687.jpg',
      // },
      // {
      //   type: 0,
      //   link: 'http://test.yuanqi.3qma.com/uploads/admin/image/202207/c093082ed79f963eede63501cf3f5687.jpg',
      // },
      // {
      //   type: 0,
      //   link: 'http://test.yuanqi.3qma.com/uploads/admin/image/202207/c093082ed79f963eede63501cf3f5687.jpg',
      // },
      // {
      //   type: 0,
      //   link: 'http://test.yuanqi.3qma.com/uploads/admin/image/202207/c093082ed79f963eede63501cf3f5687.jpg',
      // },
      // {
      //   type: 0,
      //   link: 'http://test.yuanqi.3qma.com/uploads/admin/image/202207/c093082ed79f963eede63501cf3f5687.jpg',
      // },
      // {
      //   type: 0,
      //   link: 'http://test.yuanqi.3qma.com/uploads/admin/image/202207/c093082ed79f963eede63501cf3f5687.jpg',
      // },
    ],
  };
  lockDialog.value = true;
  console.log('add', formRole.value);
};
const query = () => {
  console.log('query');
};

//页码发生改变，触发事件
const onRequest = (props: any) => {
  console.log('页码改变', props);
  const { page, rowsPerPage, rowsNumber } = props.pagination;
  initialPagination.value.page = page;
  initialPagination.value.rowsPerPage = rowsPerPage;
  initialPagination.value.per_page = rowsPerPage;
  initialPagination.value.rowsNumber = rowsNumber;

  goodsListInit();
};

const imagePath = (src: any) => {
  let path = '';
  if (src) {
    if (src.startsWith('http') || src.startsWith('https')) {
      return src;
    }
    path = `${process.env.VUE_APP_API_URL}/${src}`;
  }
  return path;
};
const Bigportrait = (src: any) => {
  console.log('1111111111111111111111111111111111111', src);
};
//恢复
const recovery = async (item: any) => {
  console.log('恢复', item);
  const res: any = await recycleRestore({ goods_id: item.goods_id });
  if (res.code == 200) {
    $q.notify({
      color: 'white',
      textColor: 'positive',
      icon: 'check_circle',
      position: 'top',
      message: res.msg,
    });
    initialPagination.value = pageInit;
    goodsListInit();
  }
};
//编辑用户
const edit = async (index: number, item: any) => {
  console.log('edit', item);
  title.value = '编辑商品';
  const detail: any = await recycleDetail({ goods_id: item.goods_id });

  //转回isform.value.sku的结构
  let data = cloneDeep(detail.data);
  data.sku.forEach((item: any, index: any) => {
    item.sku_spec_format.forEach((i: any, d: any) => {
      for (let key in i) {
        if (key == 'spec_name') {
          item[i.spec_name] = i.spec_value;
        }
      }
    });
    delete item.sku_spec_format;
  });
  //分类ID多选框字符串转数组
  data.category_id = data.category_id.split(',').map(Number);
  console.log('转回去最终结果', data);

  formRole.value = cloneDeep(data);
  formRole.value.tinymceID =
    'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '');
  lockDialog.value = true;
  // if (formRole.value.portrait == null) {
  //   formRole.value.portrait = '';
  // }
};
const deleteData = async (index: number, item: any) => {
  const res: any = await recycleDelete({ goods_id: item.goods_id });
  if (res.code == 200) {
    $q.notify({
      color: 'white',
      textColor: 'positive',
      icon: 'check_circle',
      position: 'top',
      message: res.msg,
    });
    initialPagination.value = pageInit;
    goodsListInit();
  }
};

const goodsListInit = async () => {
  lockDialog.value = false;
  tableOptions.tableLoading = true;
  const requestInfo = cloneDeep(
    Object.assign(initialPagination.value, searchForm)
  );
  const res: any = await recycleList(requestInfo);
  tableOptions.tableLoading = false;
  tableOptions.columnDatas = res.data.data;
  initialPagination.value.rowsNumber = res.data.total;
  const resCate: any = await categoryAll();
  const resType: any = await goodsTypeAll();
  cateoptions.value = resCate.data;
  goodsTypeoptions.value = resType.data;
  // const userq: any = await roleListAll();

  // useroptions.value = userq.data;
  console.log('res------------', res, resCate, resType);
};
onMounted(() => {
  goodsListInit();
});
</script>

<style scoped lang="scss">
.sc-design .sc-edit .q-item__section--side {
  padding-right: 0;
}

.q-field--dense .q-field__control {
  padding: 0 5px;
  height: 28px;
  .q-field__marginal {
    height: 28px;
  }
}
.q-field--auto-height .q-field--dense .q-field__control,
.q-field__native {
  min-height: 28px;
}
.q-gutter-x-sm,
.q-gutter-sm {
  margin-left: 15px;
}
::v-deep(.my-special-class) {
  height: 48px;
  background: #fafafa;
}
::v-deep(.my-special-class th) {
  font-size: 16px;
}
.top {
  padding-left: 10px;
}
.topLeft {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  // padding-left: 58px;
}
.topRight {
  padding-top: 10px;
}

@media screen and (max-width: 780px) {
  ::v-deep(.q-table__separator) {
    display: none;
  }
  ::v-deep(.el-input--large) {
    margin-top: 8px;
  }
}
</style>
